package com.legendframework.dao.yaml.support;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class BaseMapYml<T> extends AbstractBaseYml<T> implements IBaseMapYml<T> {

    private BaseYml<Map<String,T>> baseYml;

    private Class<T> typeClass;

    private Gson gson;

    public BaseMapYml(String path,Class<T> type) {
        typeClass = type;
        gson = new GsonBuilder().serializeNulls().create();
        baseYml = new BaseYml<>(path,null);
    }

    @Override
    public Map<String, T> getAll() {
        Map<String, T> map = baseYml.get();
        if (map == null) {
            return new HashMap<>();
        }
        for (Map.Entry<String, T> entry : map.entrySet()) {
            entry.setValue(this.get(entry.getKey()));
        }
        return map;
    }

    @Override
    public T get(String id) {
        Map<String, T> map = baseYml.get();
        if(Objects.isNull(map)){
            return null;
        }
        Object obj = map.get(id);
        if (typeClass == null) {
            return (T) obj;
        }
        return gson.fromJson(gson.toJson(obj),typeClass);
    }

    @Override
    public Boolean isExist() {
        return baseYml.isExist();
    }

    @Override
    public void isExistSave(Map<String,T> defult) {
        baseYml.existsSave(defult);
    }

    @Override
    public void delete(String id) {
        Map<String, T> map = baseYml.get();
        if(map!= null){
            map.remove(id);
            baseYml.save(map);
        }
    }

    @Override
    public synchronized void save(String id,T t) {
        Map<String, T> map = baseYml.get();
        if(Objects.isNull(map)){
            map = new HashMap<>();
        }
        map.put(id,t);
        baseYml.save(map);
    }
}
